
/**
 * Module dependencies.
 */


var express = require('express')
  , routes = require('./routes')
  , path = require('path')
  , sio = require('socket.io')
  , app = express()
  , server = require('http').createServer(app)
  , io = sio.listen(server,{
    'log level': 1
  })
  , fs = require('fs');
var mongoose = require('mongoose');
mongoose.connect('mongodb://127.0.0.1:27017/gltalk');
var errorLogfile = fs.createWriteStream('./log/error.log', {flags: 'a'});
app.configure(function(){
  app.use(express.logger('dev'));
  app.set('port', process.env.PORT || 3000);
  app.set('views', __dirname + '/views');
  // app.set('view engine', 'ejs');
  app.set('view engine', 'jade'); 
  // app.set('view options', {layout: false});
  app.set('view cache', true);
  app.use(express.favicon());
  app.use(express.static(path.join(__dirname, 'public')));
  app.use(express.logger('dev'));
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(app.router);
  // app.use(express.vhost('hiyo'))
});
app.use(function (err, req, res, next) {
  console.log('hello error' );
  var meta = '[' + new Date() + ']' + req.url + '\n';
  errorLogfile.write(meta + err.stack + '\n');
  next();
});
// app.configure('development', function(){
//   app.use(express.errorHandler());
// });
history = [];
routes(app);

function htmlEntities(str){
  return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot');
}
io.configure(function(){
  io.set('authorization', function(handshakeData, callback){
    var pattern = /chat\.hiyo\.in/i;
    if (pattern.test(handshakeData.headers.referer)){
      callback(null, true);
    }else{
      callback(null, false);
    }          
  });
});
function saveFile(data) {
    data = JSON.stringify(data);
    fs.writeFile('./log/history.json', data, 'utf8', function(err){
      console.log('add end' + new Date());
  })
}
function setHis(data,callback){
  console.log('load history');
  history = JSON.parse(data);
  console.log(history);
  callback();
}
var saveHis = setInterval(function(){
  if (history.length > 0){
    saveFile(history);
  }
}, 100000);
io.sockets.on('connection', function (socket,handshakeData) {
  socket.on('getHistory',function(){
    if (history.length > 0){
      socket.emit('history',history);
    //} else if(path.existsSync('./log/history.json')){
    }else{
      // console.log('has history')
      fs.readFile('./log/history.json', 'utf8', function(err, data){
        if(err) console.log(err);
        setHis(data,function(){
          socket.emit('history',history);
        });
      });
    }
  });
  socket.on('newuser', function(msg){
      // msg = htmlEntities(msg);
      socket.broadcast.emit('sys', msg);
    });
  socket.on('msg', function (data) {
    data.msg = htmlEntities(data.msg);
    data.name = htmlEntities(data.name);
    data.time = new Date().toLocaleTimeString();
    if(data.to==undefined||data.to==''){
      history.push(data);
      history = history.slice(-50);
      //saveFile(history);
    }
    socket.broadcast.emit('news',data);
    socket.emit('news',data);
  });
});
server.listen(app.get('port'), function(){
  console.log("Express server listening on port " + app.get('port'));

});